package com.flyduck.system.dao;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.flyduck.system.entity.SysUserRoleEntity;
import com.flyduck.system.mapper.SysUserRoleMapper;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @program: flyduck-platform2
 * @description:
 * @author: flyduck
 * @create: 2021-04-23 14:48
 **/
@Repository
public class SysUserRoleDao extends ServiceImpl<SysUserRoleMapper, SysUserRoleEntity> {

    /**
     * 根据用户id获取角色id集合
     * @param userId
     * @return
     */
    public List<Long> getRoleIdsByUserId(Long userId) {
        List<SysUserRoleEntity> sysUserRoleEntityList = this.baseMapper.selectList(
                new QueryWrapper<SysUserRoleEntity>().eq("user_id", userId)
        );
        return sysUserRoleEntityList.stream().map(SysUserRoleEntity::getRoleId).collect(Collectors.toList());
    }

    /**
     * 新增用户职位关系集合
     * @param userId
     * @param roleIds
     * @return
     */
    public int insertUserRoleList(Long userId, List<Long> roleIds) {
        int rows = 0;
        for (Long roleId : roleIds) {
            SysUserRoleEntity sysUserRoleEntity = new SysUserRoleEntity();
            sysUserRoleEntity.setUserId(userId);
            sysUserRoleEntity.setRoleId(roleId);
            int row = this.baseMapper.insert(sysUserRoleEntity);
            rows += row;
        }
        return rows;
    }

    /**
     * 根据用户id删除用户角色关系
     * @param userId
     * @return
     */
    public int deleteByUserId(Long userId) {
        return this.baseMapper.delete(new QueryWrapper<SysUserRoleEntity>().eq("user_id", userId));
    }
}
